#include "mqttwidget.h"
#include "qevent.h"
#include <QDebug>

MqttWidget::MqttWidget(QWidget *parent) :
    QFrame(parent)
{
    this->show();
    this->setMouseTracking(true);
    this->setFocusPolicy(Qt::StrongFocus);       //鼠标点击聚焦
    gridLayout = new QGridLayout(this);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    this->setLayout(gridLayout);
    this->resize(200,120);
}

MqttWidget::~MqttWidget()
{
}

void MqttWidget::setData(MqttData data)
{
    mData = data;
}

MqttData MqttWidget::getData()
{
    return mData;
}

void MqttWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        pressed = true;
        globalPos = event->globalPos();
        basicSize = size();
    }
    else
        showMenu(mapToGlobal(event->pos()));
}
void MqttWidget::mouseReleaseEvent(QMouseEvent*)
{
    pressed = false;
}
void MqttWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(pressed)
    {
        QPoint p = event->globalPos();
        if(canMove)
        {
            QSize tempSize = basicSize;
            if(moveType & 1)
            {
                int width = basicSize.width() + p.x() - globalPos.x();
                tempSize.setWidth(width >= 50 ? width : 50);
            }
            if(moveType & 2)
            {
                int height = basicSize.height() + p.y() - globalPos.y();
                tempSize.setHeight(height >= 50 ? height : 50);
            }
            resize(tempSize);
        }
        else
        {
            this->move(x() - globalPos.x() + p.x(), y() - globalPos.y() + p.y());
            globalPos = p;
        }
    }
    else
    {
        moveType = 3;
        moveType &= (event->pos().x() + 10 >= width() ? 255 : 254);
        moveType &= (event->pos().y() + 10 >= height() ? 255 : 253);
        switch (moveType)
        {
            case 0: setCursor(Qt::ArrowCursor);break;
            case 1: setCursor(Qt::SizeHorCursor);break;
            case 2: setCursor(Qt::SizeVerCursor);break;
            case 3: setCursor(Qt::SizeFDiagCursor);break;
            default: break;
        }
        canMove = (moveType > 0);
    }
}

#include<QColor>
void MqttWidget::focusInEvent(QFocusEvent *e)
{
    Q_UNUSED(e)
    isFocus = 1;
    this->setStyleSheet(QString::fromUtf8("border:3px solid blue"));
}

void MqttWidget::focusOutEvent(QFocusEvent *e)
{
    Q_UNUSED(e)
    isFocus = 0;
    this->setStyleSheet("");
}

#include <QMenu>
#include "addmqttdialog.h"
void MqttWidget::showMenu(const QPoint &pos)
{
    QMenu menu;

    menu.addAction("编辑",[=](){
        AddMqttDialog editDialog("编辑",this);
        editDialog.setData(mData);
        if(editDialog.exec() == QDialog::Rejected)
            return ;
        mData = editDialog.getData();//将编辑界面的数据保存到类数据
    });
    menu.addAction("删除",[=](){
        deleteThis(id);
    });
    menu.exec(pos);
}




